const moment = require("../../miniprogram_npm/moment/index.js")
var Protocol = require ("../../Controls/Protocol")
var Login = require("../../Controls/Login")
var util = require ("../../utils/util")
var DataExchange = require ("../../Controls/DataExchange")
var UploadFile = require("../../Controls/UploadFile")
const pay = require('../../utils/pay')
import Dialog from '../../miniprogram_npm/vant-weapp/dialog/dialog.js'

var app = getApp();

var isStarted = false;

var delta = 1;

var data =
  {
    isLogin: false,

    isHideContinue:true,
    isHideHomeSingle:true,
    isHideLogin:true,
    isHideBuy:false,
    isHideHome:true,

    isFold:true,
    //是否预览发布的秘袋数据
    isPreview:true,

    //是否购买成功
    isGot:false,

    indicatorDots: true,
    autoPlay: false,
    interval: 1000,
    duration: 300,

    showResult: false,
    transactionPrice:0,
    sellerUrl:"",

    rate:0,

    seller:
    {
      avatar:"../../image/icon_small.png",
      nickname:"empty",
      userId:-1
    },

    timeStr:
    {
      h: "00",
      m: "00",
      s: "00",
    },

    product_info:
    {
      id: 1,
      name: "商品名称",
      price: 0,
      max_price: 999,
      min_price: 0,
      left_time: 0,
      images: ["../../image/icon_small.png"],
      left_count:0,
      desc:"这是秘袋描述",
      qty:0,
    },

    other_userinfo:
    [
      //{ userId: -1, nickname: "熊大", avatar: "../../image/icon_small.png", qty: 10.00, },
      //{ userId: -2, nickname: "熊二", avatar: "../../image/icon_small.png", qty: 10.00, }
    ],

    buyer_userinfo:
    [
        //{ userId: -1, avatar: "../../image/yellowchild.jpg" },
    ],
  }

var barginOption = 
{
  success:function(that, res)
  {
    var newOther = new Array();
    for(var i = 0; i < that.data.other_userinfo.length; i++)
    {
      newOther.push(that.data.other_userinfo[i]);
    }

    newOther.push({
      userId: app.globalData.userInfo.userId,
      nickname: app.globalData.userInfo.nickName,
      avatar: app.globalData.userInfo.avatarUrl
    });

    var newInfo = {
      id:that.data.product_info.id,
      price: that.data.product_info.price - res.data.data.discount,
      max_price: that.data.product_info.max_price,
      min_price: that.data.product_info.min_price,
      left_time: that.data.product_info.left_time,
      images: that.data.product_info.images,
      left_count: that.data.product_info.left_count,
      desc: that.data.product_info.desc,
      qty: that.data.product_info.qty
    };

    that.setData({
      isLogin:true,
      isHideHome:false,
      other_userinfo:newOther,
      product_info: newInfo
    });

    that.BarginPop.showDialog(`您使用爆破忍术，秘袋额外降价${res.data.data.discount}元 再接再厉，更多惊喜在等着您哦！`);
  },
  fail:function(that, res)
  {
    console.log("bargin 失败");
  }
}

var queryOption = 
{
  success:function(that, res)
  {
    var data = res.data.data;

    isStarted = false;

    var left = 0;
    var now = moment();
    var expireTime = moment(data.expireTime);

    if (now < expireTime)
    {
      isStarted = true;
      left = Math.floor((expireTime - now).valueOf() / 1000);
    }

    var isHideLogin = false;

    if(app.globalData.isLogin)
    {
      isHideLogin = true;
    }

    if(data.seller.userId == app.globalData.userInfo.userId)
    {
      isHideLogin = true;
    }

    if(left <= 0)
    {
      isHideLogin = true;
    }

    var isHideHomeSingle = true;
    if(isHideLogin)
    {
      if(left <= 0)
      {
        isHideHomeSingle = false;
      }
    }

    var isHideContinue = true;
    if(data.seller.userId == app.globalData.userInfo.userId)
    {
      isHideContinue = false;
    }

    const bargins = new Array();
    bargins.push(data.bargains[0]);
    bargins.push(data.bargains[0]);
    bargins.push(data.bargains[0]);
    bargins.push(data.bargains[0]);
    bargins.push(data.bargains[0]);
    bargins.push(data.bargains[0]);
    bargins.push(data.bargains[0]);
    bargins.push(data.bargains[0]);
    bargins.push(data.bargains[0]);


    that.setData({
      isHideContinue: isHideContinue,
      isHideHomeSingle:isHideHomeSingle,
      isHideLogin: isHideLogin,
      isHideHome: !app.globalData.isLogin || data.seller.userId == app.globalData.userInfo.userId,
      isHideBuy: left<=0 || data.qty <= 0 || data.seller.userId == app.globalData.userInfo.userId,
      seller: data.seller,
      rate: ((data.maxPrice - data.price) / data.maxPrice * 100).toFixed(2),
      product_info:
      {
        userId:data.userId,
        id: data.id,
        name: data.name,
        price: data.price,
        max_price: data.maxPrice,
        min_price: data.minPrice,
        left_count: data.qty,
        images: data.images.split(","),
        left_time: left,
        desc: data.desc,
        qty: (data.maxPrice - data.price).toFixed(2),
      },
      timeStr: util.getLeftTimeStr(left),
      other_userinfo: bargins//data.bargains,
    });

    if (app.globalData.isLogin && data.userId != app.globalData.userInfo.userId) 
    {
      var isBargin = false;
      for (var i = 0; i < data.bargains.length; i++)
      {
        if(data.bargains[i].userId == app.globalData.userInfo.userId)
        {
          isBargin = true;
          break;
        }
      }

      if (!isBargin && left > 0 && data.qty > 0 && data.price > 0)
      {
        Protocol.bargain(data.id, {
          success:function(res)
          {
            console.log(res)
            if(res.data.code == 0)
            {
              barginOption.success(that, res);
            }
            else
            {
              barginOption.fail(that, res);
            }
          },
          fail:function(res)
          {
            console.log(res)
            barginOption.fail(that, res);
          }
        });
      }
    }
  },
  fail: function (that, res)
  {
    console.log(res);
  }
}

var onTimer = function(that)
{
  if (!isStarted)
  {
    return;
  }

  that.data.product_info.left_time = that.data.product_info.left_time - 1;
  that.setData({ timeStr: util.getLeftTimeStr(that.data.product_info.left_time)});

  if(that.data.product_info.left_time == 0)
  {
    console.log("时间到！");
    isStarted = false;
  }
}

var startTimer = function(that, duration)
{
  setTimeout(function(){onTimer(that); startTimer(that, duration)}, duration);
}

var onPreview = function (that)
{ 
  var data = DataExchange.get_publishData();
  var seller = 
  {
    nickname: app.globalData.userInfo.nickName,
    avatar: app.globalData.userInfo.avatarUrl,
    userId: app.globalData.userInfo.userId
  };
  that.setData({
    isHideContinue: true,
    isHideHomeSingle:true,
    isHideLogin:true,
    isHideBuy: true,
    isHideHome: true,
    seller: seller,
    product_info:
    {
      userId: app.globalData.userInfo.userId,
      name: data.name,
      price: data.maxPrice,
      max_price: data.maxPrice,
      min_price: data.minPrice,
      left_time: data.duration,
      images: data.images,
      left_count: data.qty,
      desc: data.desc,
    },
    timeStr:util.getLeftTimeStr(data.duration),
  });
}

var onPull = function(that, id)
{
  Protocol.productDetail(id, {
    success: function (res) {
      if (res.data.code == 0) {
        queryOption.success(that, res);
      }
      else {
        queryOption.fail(that, res);
      }

    },
    fail: function (res) {
      queryOption.fail(that, res);
    }
  });
}

function onLoad(option)
{
  startTimer(this, 1000);

  var that = this;

  var preview = option.preview || false;
  if(option.delta)
  {
    delta = parseInt(option.delta)
  }
  else
  {
    delta = 1;
  }

  this.setData({ isPreview: preview })
  this.setData({isLogin:app.globalData.isLogin})

  this.Tip = this.selectComponent("#Tip");
  this.BarginPop = this.selectComponent("#BarginPop");

  if (preview)
  {
    onPreview(that);
  }
  else
  {
    onPull(that, option.id);
  }
}

function onReady() 
{
}

function btnJoinusIvk()
{
  if(app.globalData.isLogin)
  {
    wx.switchTab({
      url: '../../pages/selecttype/selecttype',
      success:function(res)
      { console.log("1" + res);},
      fail:function(res)
      { console.log("2" + res);},
      complete:function()
      {
        console.log("3");
      }
    })
  }
  else
  {
    wx.switchTab({url: '../../pages/my/my'});
  }
}

function btnContinueIvk()
{
  wx.switchTab({
    url: '../../pages/selecttype/selecttype',
  })
}

function btnLoginIvk()
{
  var id = this.data.product_info.id;
  wx.reLaunch({
    url: `../login/login?frompath=../product/product&id=${id}`,
  })
}

function btnShareFriendIvk() {
  console.log("召唤好友");
}

function btnHelpIvk() {
  this.Tip.showDialog("秘袋屋规则", "若卖家未在36小时内发货，您将或得68元现金及170元优惠券补偿。");
}

function btnBuyIvk() {
  const that = this;
  
  if (app.globalData.credit.balance < this.data.product_info.price)
  {
    const order =
    {
      amount: parseInt((this.data.product_info.price - app.globalData.credit.balance) * 100),
      body: '账号充值'
    };

    pay(order, {
      success: () => {
        that.btnBuyIvk();
      },
      fail: () => {
        Dialog.alert({ message: "充值失败!", zIndex:9999});
      }
    })
    return;
  }

  Protocol.buy(parseInt(this.data.product_info.id), {
    success:(res) =>
    {
      if(res.data.code == 0)
      {
        that.setData({ showResult: true,
         transactionPrice: res.data.data.price,
         sellerUrl: res.data.data.qrcode});
      }
    },
    fail:() =>
    {
      Dialog.alert({message: "购买失败!", zIndex:9999});
    }
  });


  return;
  //不要确认订单之后的所有操作了，购买之后直接联系商家
  if(!app.globalData.isLogin)
  {
    var id = this.data.product_info.id;
    wx.reLaunch({
      url: `../login/login?frompath=../product/product&id=${id}`,
    })
    return;
  }


  DataExchange.set_productData(this.data.product_info);
  wx.navigateTo({
    url: '../confirmorder/confirmorder',
  })
}


//自定义分享内容
function onShareAppMessage(options)
{ 
  this.BarginPop.hideDialog();

  var id = this.data.product_info.id;

  var ret = 
  {
      title:"你的好友发动了黑市，快去围观~",
      path: `/pages/product/product?id=${id}`,
      //imageUrl:"../../image/yellowchild.jpg", 不指定url会截屏高度80%屏幕宽度
  }

  return ret;
}

function btnPublishIvk()
{
  console.log("发布");
  var data = DataExchange.get_publishData();

  var that = this;

  var publishResult = 
  {
    success:function(res)
    {
      console.log(res);
      util.showSuccess("发布成功");
      wx.reLaunch({
        url: `../../pages/product/product?id=${res.data.data.id}`,
      })
    },
    fail:function(res)
    {
      util.showModel("发布失败", JSON.stringify(res));
    },
    complete:function()
    {

    }
  };

  var doPublish = function (images, publishResult)
  {
    Protocol.publish(
      {
        images:images.join(","),
        name: data.name,
        maxPrice: data.maxPrice,
        minPrice: data.minPrice,
        qty: data.qty,
        desc: data.desc,
        duration: data.duration,
      }, publishResult
    );
  }

  UploadFile.uploadFiles(data.images, {
    success:function(res)
    {
      console.log("上传成功");
      console.log(res);
      doPublish(res.successPaths, publishResult);
    }, 
    fail:function()
    {
      console.error("图片上传失败,点击重试");
    }
  });
}

function btnEditIvk()
{
  wx.navigateBack({
    delta: delta,
  })
}

function toggle()
{
  this.setData({isFold:!this.data.isFold})
}

function onDrag(event)
{
  const rate = this.data.rate;
  this.setData({rate: rate});
}

function onChange()
{
  const rate = this.data.rate;
  this.setData({ rate: rate });
}

var operation =
{
  data,
  onLoad,
  onReady,
  btnShareFriendIvk,
  btnJoinusIvk,
  btnHelpIvk,
  btnBuyIvk,
  btnEditIvk,
  btnPublishIvk,
  onShareAppMessage,
  toggle,
  btnLoginIvk,
  btnContinueIvk,
  onDrag,
  onChange,
};

Page(operation)

